<?php
header( 'Content-Type:text/html;charset=utf-8 ');
require_once ("utils/R.php");
require_once ("utils/MySQL.php");
//开启一个会话
session_start();
$r = new R();
$db = MySQL::getInstance();
if (!isset($_REQUEST['type'])) {
    echo $r->result(500,"非法请求","");
} else {
    $type = $_REQUEST['type'];
    switch ($type){
        //添加用户
        case "add_user":{
            $command = file_get_contents("php://input");
            $data =json_decode( $command,true);//true,转化成数组
            if($data){
                //判断用户是否已经注册
                $sql = "select id from wx_user where username='".$data["username"]."'";
                $result = $db->fetchOne($sql,2);
                if($result){
                    echo $r->result(500,"添加失败，该用户已经被注册","");
                }else{
                    $sql = "insert into wx_user(nick_name,gender,avatar_url,username,password) VALUES ('".$data["nickName"]."',".$data["gender"].",'".$data["avatarUrl"]."','".$data["username"]."','".md5($data["password"])."')";
                    $result = $db->exec($sql);
                    //查询用户数据
                    $sql = "select id from wx_user where username='".$data["username"]."'";
                    $result = $db->fetchOne($sql,2);
                    if($result){
                        echo $r->result(200,"添加成功",$result);
                    }else{
                        echo $r->result(500,"添加失败","");
                    }

                }
            }else{
                echo $r->result(500,"添加失败，用户数据为null","");
            }
            break;
        }
        //登录
        case "login":{
            $command = file_get_contents("php://input");
            $data =json_decode( $command,true);//true,转化成数组
            if($data){
                //判断用户是否已经注册
                $sql = "select * from wx_user where username='".$data["username"]."' and password = '".md5($data["password"])."'";
                $result = $db->fetchOne($sql,2);
                if($result){
                    echo $r->result(200,"登录成功",$result);
                }else{
                    echo $r->result(500,"用户名或者密码错误","");
                }
            }else{
                echo $r->result(500,"用户名或者密码不可为null","");
            }
            break;
            break;
        }
        //获取所有的投票类型
        case "questionnaire_type":{
            $sql = "select * from wx_questionnaire_type";
            $result = $db->fetchAll($sql,2);
            if($result){
                echo $r->result(200,"数据获取成功",$result);
            }else{
                echo $r->result(500,"数据为null","");
            }
            break;
        }
        //获取导出数据
        case "getDatas":{
            $sql = "select * from wx_vote as wv LEFT JOIN wx_vote_info wvi on wv.id = wvi.vote_id right JOIN wx_vote_answer as wva on wvi.id = wva.vote_info_id";
            $result = $db->fetchAll($sql,2);
            if($result){
                echo $r->result(200,"数据获取成功",$result);
            }else{
                echo $r->result(500,"数据为null","");
            }
            break;
        }
        //投票功能
        case "vote":{
            //先查询所有投票信息
            $qId = $_REQUEST['q_id'];
            $keyword = $_REQUEST['keyword'];
            if($qId>1){
                $sql = "select * from wx_vote where q_id=".$qId;
            }else if($keyword){
                $sql = "select * from wx_vote where title like '%".$keyword."%'";
            }else{
                $sql = "select * from wx_vote";
            }
            $result = $db->fetchAll($sql,2);
            if($result){
                echo $r->result(200,"数据获取成功",$result);
            }else{
                echo $r->result(500,"数据为null","");
            }
            break;
        }
        //添加投票
        case "add_vote":{
            $command = file_get_contents("php://input");
            $data =json_decode( $command,true);//true,转化成数组
            if($data){
                //先添加投票信息
                $sql = "insert into wx_vote(title,q_id) VALUES ('".$data["title"]."',".$data["qId"].")";
                $result = $db->exec($sql);
                //在查询出id投票的
                $sql = "select id from wx_vote ORDER BY id desc limit 1";
                $result = $db->fetchOne($sql,2);
                //再添加题目和选项
                $subject = $data["subject"];
                //循环添加
                //            insert into wx_vote_info(subject,answer_option,vot…id":2,"option":"dd"},{"id":3,"option":"qq"}]',,1)
                $voteId = $result["id"];
                for($i=0;$i<count($subject);$i++){
                    $option = json_encode($subject[$i]["options"],JSON_UNESCAPED_UNICODE);
                    $sql = "insert into wx_vote_info(subject,answer_option,vote_id,subject_type) VALUES ('".$subject[$i]["subjectTitle"]."','".$option."',".$voteId.",".$subject[$i]["subjectType"].")";
                    $result = $db->exec($sql);
                }
                echo $r->result(200,"添加投票成功",$data);
            }else{
                echo $r->result(500,"参数不可为null","");
            }
            break;
        }
        //删除问卷
        case "del_vote":{
            $id = $_REQUEST["id"];
            if($id>0){
                $sql = "delete from wx_vote where id = ".$id;
                $result = $db->exec($sql);
                echo $r->result(200,"删除成功",$result);
                return;
            }
            echo $r->result(500,"参数不可为null","");
            break;
        }
        //投票功能
        case "vote_ifo":{
            $voteId = $_REQUEST['vote_id'];
            if($voteId){
                //先查询所有投票信息
                $sql = "select * from wx_vote_info where vote_id = ".$voteId;
                $result = $db->fetchAll($sql,2);
                if($result){
                    echo $r->result(200,"数据获取成功",$result);
                }else{
                    echo $r->result(500,"数据为null","");
                }
            }else{
                echo $r->result(500,"非法请求","");
            }
            break;
        }
        //添加投票信息
        case "add_vote_info":{
            $subject = $_REQUEST['subject'];
            $option = $_REQUEST['answer_option'];
            $voteId = $_REQUEST['vote_id'];

            if($subject&&$option&&$voteId){
                //先查询所有投票信息
                $sql = "insert into wx_vote_info(subject,answer_option,vote_id) VALUES ('".$subject."','".$option."',".$voteId.")";
                $result = $db->exec($sql);
                if($result){
                    echo $r->result(200,"添加投票详情成功",$result);
                }else{
                    echo $r->result(500,"添加投票详情失败","");
                }
            }else{
                echo $r->result(500,"参数不可为null","");
            }
            break;
        }
        //添加答题
        case "add_vote_answer":{
            $command = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
            $data =json_decode( $command,true);//true,转化成数组
            if($data){
                $d = json_decode($data["data"],true);
                if($d){
                    for($i=0;$i<count($d);$i++){
                        $sql = "insert into wx_vote_answer(username,answer,vote_info_id) VALUES ('".$d[$i]['username']."','".$d[$i]['answer']."',".$d[$i]['vote_info_id'].")";
                        $result = $db->exec($sql);
                    }
                    echo $r->result(200,"提交成功","");
                }else{
                    echo $r->result(500,"提交失败","");
                }
            }else{
                echo $r->result(500,"参数不可为null",$data);
            }
            break;
        }
        //导出数据
        case "exportData":{
            include './utils/ExportData.php';
            break;
        }
        //统计数据
        /**
         * subjects:[
                {
                "subject":"你是GG还是MM",
                "subject_type":1,
                "answer_option":[
                    {
                    "id": 0,
                    "option": "GG",
                    "count":"20",
                    "proportion":"60"
                    },
                    {
                    "id": 1,
                    "option": "MM",
                    "count": "10",
                    "proportion": "40"
                    }
                ]
                }
            ]
         */
        case "countData":{
            $voteId = $_REQUEST["id"];
            if($voteId>0){
                $data = array(
                    "subjects"=>array(
                        array(
                            "subject"=>"",
                            "subject_type"=>0,
                            "answer_option"=>array(
                                array(
                                    "id"=>0,
                                    "option"=>"",
                                    "count"=>"",
                                    "proportion"=>"",
                                )
                            ),
                        )
                    )
                );
                //查询投票下的所有题目
                $voteSql = "SELECT * from wx_vote_info WHERE vote_id = ".$voteId;
                $votes = $db->fetchAll($voteSql,2);
                //遍历题目
                if($votes){
                    $subjects = array();
                    for($x=0;$x<count($votes);$x++){
                        $id = $votes[$x]["id"];
                        //查询总条数
                        $countSql = "select count(id) FROM wx_vote_answer where vote_info_id = ".$id;
                        $count = $db->fetchOne($countSql);
                        //查询所有的题目
                        $sql = "SELECT * from wx_vote_info wvi LEFT JOIN wx_vote_answer wva on wvi.id = wva.vote_info_id WHERE wvi.id = ".$id;
                        $result = $db->fetchAll($sql,2);
                        //遍历数据
                        if($result){
                            $subject = array();
                            for($i=0;$i<1;$i++){
                                //遍历每个题目
                                $options = json_decode($result[$i]["answer_option"]);
                                //遍历每个题目下的选项
                                $answerOptions = array();
                                if($options){
                                    for($j=0;$j<count($options);$j++){
                                        //查询单个选项阁主
                                        $on = $options[$j]->id;
                                        if($on=="1"){
                                            $ar = "a";
                                        }else if($on=="2"){
                                            $ar = "b";
                                        }else if($on=="3"){
                                            $ar = "c";
                                        }else{
                                            $ar = "d";
                                        }
                                        $countSql = "select count(id) FROM wx_vote_answer where vote_info_id = ".$id." and answer ='".$ar."'";
                                        $answerCount = $db->fetchOne($countSql);

                                        //封装选项
                                        if($count[0]>0){

                                            $num = ($answerCount[0]/$count[0])*100;

                                        }else{
                                            $num = 0;
                                        }
                                        $ao = array(
                                            "id"=>$options[$j]->id,
                                            "option"=>$options[$j]->option,
                                            "count"=>$answerCount,
                                            "proportion"=>round($num,2),
                                        );
                                        $answerOptions[] = $ao;

                                    }
                                }
                                //添加到每个题目下面
                                $subject = array(
                                    "subject"=>$result[$i]["subject"],
                                    "subject_type"=>$result[$i]["subject_type"],
                                    "answer_option"=>$answerOptions
                                );
                            }
                            $subjects[] = $subject;
                        }
                    }
                    $data["subjects"] = $subjects;
                }
                //查询总数
                echo $r->result(200,"获取成功",$data);
                return;
            }
            echo $r->result(500,"id为null","");
            break;
        }
    }
}


